<template>
  <div class="profile-edit-page" v-loading="loading">
    <div class="edit-container">
      <div class="edit-header">
        <h1>编辑个人资料</h1>
        <div class="header-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="edit-form"
      >
        <!-- 头像上传 -->
        <el-form-item label="头像">
          <div class="avatar-upload">
            <el-avatar
              :size="100"
              :src="getMediaUrl(form.avatar)"
              class="avatar-preview"
            >
              {{ form.nickname?.charAt(0) || userStore.userInfo?.username?.charAt(0) }}
            </el-avatar>
            <div class="upload-actions">
              <el-upload
                ref="uploadRef"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                name="file"
                accept="image/*"
              >
                <el-button type="primary" size="small">更换头像</el-button>
              </el-upload>
              <el-button 
                v-if="form.avatar" 
                size="small" 
                @click="removeAvatar"
              >
                移除头像
              </el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 昵称 -->
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="form.nickname"
            placeholder="请输入昵称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <!-- 个人简介 -->
        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="form.bio"
            type="textarea"
            placeholder="介绍一下自己吧..."
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio :label="0">保密</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 生日 -->
        <el-form-item label="生日">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <!-- 所在地 -->
        <el-form-item label="所在地" prop="location">
          <el-input
            v-model="form.location"
            placeholder="请输入所在地"
            maxlength="100"
          />
        </el-form-item>

        <!-- 个人网站 -->
        <el-form-item label="个人网站" prop="website">
          <el-input
            v-model="form.website"
            placeholder="请输入个人网站"
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="form.email"
            placeholder="请输入邮箱"
            type="email"
          />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>

        <!-- 隐私设置 -->
        <el-form-item label="隐私设置">
          <el-radio-group v-model="form.isPrivate">
            <el-radio :label="0">公开资料</el-radio>
            <el-radio :label="1">私密账户</el-radio>
          </el-radio-group>
          <div class="form-tip">
            私密账户只有关注者可以看到您的内容
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {useUserStore} from '@/stores/user'
import {getCurrentUserInfo, updateUserInfo} from '@/api/user'
import {getMediaUrl} from '@/utils/media'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const formRef = ref()
const uploadRef = ref()

// 表单数据
const form = reactive({
  nickname: '',
  avatar: '',
  bio: '',
  gender: 0,
  birthday: '',
  location: '',
  website: '',
  email: '',
  phone: '',
  isPrivate: 0
})

// 表单验证规则
const rules = {
  nickname: [
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  bio: [
    { max: 500, message: '个人简介长度不能超过500个字符', trigger: 'blur' }
  ],
  location: [
    { max: 100, message: '所在地长度不能超过100个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 上传配置
const uploadUrl = '/api/quora/attach/uploadFile'
const uploadHeaders = computed(() => {
  return userStore.token ? {
    'authorization': userStore.token
  } : {}
})

// 生命周期
onMounted(() => {
  loadUserInfo()
})

// 方法
const loadUserInfo = async () => {
  loading.value = true
  try {
    const response = await getCurrentUserInfo()
    if (response.code === 200) {
      const userInfo = response.data
      Object.assign(form, {
        nickname: userInfo.nickname || '',
        avatar: userInfo.avatar || '',
        bio: userInfo.bio || '',
        gender: userInfo.gender || 0,
        birthday: userInfo.birthday || '',
        location: userInfo.location || '',
        website: userInfo.website || '',
        email: userInfo.email || '',
        phone: userInfo.phone || '',
        isPrivate: userInfo.isPrivate || 0
      })
    } else {
      ElMessage.error(response.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess = (response) => {
  console.log('上传成功响应:', response)
  if (response.code === 200) {
    // 使用后端返回的 filePath
    form.avatar = response.data.filePath
    ElMessage.success('头像上传成功')
    console.log('头像路径已更新:', form.avatar)
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

const handleAvatarError = () => {
  ElMessage.error('头像上传失败')
}

const removeAvatar = () => {
  form.avatar = ''
  ElMessage.success('头像已移除')
}

const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }

  saving.value = true
  try {
    const response = await updateUserInfo(form)
    if (response.code === 200) {
      ElMessage.success('保存成功')
      // 更新用户store中的信息
      await userStore.refreshUserInfo()
      router.push(`/people/${userStore.userInfo.userId}`)
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const goBack = () => {
  router.back()
}
</script>

<style scoped>
.profile-edit-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.edit-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #f0f0f0;
}

.edit-header h1 {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.edit-form {
  padding: 30px;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-preview {
  border: 2px solid #f0f0f0;
}

.upload-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-tip {
  font-size: 12px;
  color: #8590a6;
  margin-top: 4px;
}

@media (max-width: 768px) {
  .edit-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .avatar-upload {
    flex-direction: column;
    text-align: center;
  }
}
</style>
